using Jwt.AuthenticationCenter.Utility;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Reflection;
using System.Text;
using WebAPI.Utility;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

// Add services to the container.

// 手动添加控制器，排除Jwt.AuthenticationCenter项目的控制器
builder.Services.AddControllers()
    .ConfigureApplicationPartManager(manager =>
    {
        var jwtAuthCenterPart = manager.ApplicationParts
            .FirstOrDefault(part => part.Name == "Jwt.AuthenticationCenter");
        if (jwtAuthCenterPart != null)
        {
            manager.ApplicationParts.Remove(jwtAuthCenterPart);
        }
    });
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    foreach(FieldInfo fieId in typeof(ApiVersionInfo).GetFields())
    {
        c.SwaggerDoc(fieId.Name, new Microsoft.OpenApi.Models.OpenApiInfo()
        {
            Title = $"WebAPI-{fieId.Name}",
            Version = fieId.Name,
            Description = $"这是{fieId.Name}版本的接口文档",
        });
    }
    #region 为Swagger JSON和UI添加xml文档注释路径 
    string basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序的当前目录路径，可能会受运行目录影响，所以采用此方法获取路径
    string xmlPath = Path.Combine(basePath, "WebApi.xml");
    c.IncludeXmlComments(xmlPath);
    #endregion
});

{
    #region jwt验证  HS
    {
        //第二步：添加认证逻辑
        JWTTokenOptions tokenOptions = new JWTTokenOptions();
        builder.Configuration.Bind("JWTTokenOptions", tokenOptions);
        builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//Scheme
         .AddJwtBearer(options =>  //配置使用的认证逻辑
         {
             options.TokenValidationParameters = new TokenValidationParameters
             {
                 //JWT的一些默认的参数，这些是认证时就可以筛选的
                 ValidateIssuer = true,//是否验证Issuer
                 ValidateAudience = true,//是否验证Audience
                 ValidateLifetime = true,//是否验证失效时间
                 ValidateIssuerSigningKey = true,//是否验证SecurityKey
                 ValidAudience = tokenOptions.Audience,//
                 ValidIssuer = tokenOptions.Issuer,//Issuer必须和之前签名jwt的一致
                 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey))//得到SecurityKey 
             };
         });
    }
    #endregion
}

var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
//    app.UseSwagger();
//    app.UseSwaggerUI();
//}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    foreach (FieldInfo fieId in typeof(ApiVersionInfo).GetFields())
    {
        c.SwaggerEndpoint($"/swagger/{fieId.Name}/swagger.json", $"WebAPI-{fieId.Name}");
    }
});
//app.UseHttpsRedirection();


#region 认证授权

app.UseAuthentication();//认证
app.UseAuthorization();//授权

#endregion

app.MapControllers();

app.Run();
